<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Pointers III
</title>
  <meta
 content="C++ Tutorial: Function Pointer" name="description" />
  <meta
 content="C++ Tutorial, Function Pointer, Returning a Pointer, Pointers to Functions, Null Pointers"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Pointers III</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers I</a></li>
   <li><a href="pointers2.html">Pointers II - void*, Pointer/Array, and Pointer to Pointer</a></li>
   <li><a href="pointers3.html">Pointers III - Pointer to Function, Null Pointer</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>

<br />
<br />

<img src="images/pointers3/SumJinKang.png" alt="SumJinKang"/>
<br />
<br />

<br />
<div class="bodytext" style="padding: 12px;" align="justify">

<div class="subtitle" id="returningpointer">Returning a Pointer</div>
<p>Not long time ago, before references came out, the only option programmers had for returning objects from functions was using pointers. References provide a cleaner syntax we may still need to return objects through pointers.</p>
<p>The example below demonstrates returning pointers. Through the returned pointers, the code displays and modifies the values of a vector that holds the name of composers.</p>
<pre>
#include &lt;iostream&gt;  
#include &lt;vector&gt;
#include &lt;string&gt;

using namespace std;

string *getComposer(vector<string> *const pVec, int i) {
	return &amp;((*pVec)[i]);
}

int main()  
{  	
	vector<string> composers;
	composers.push_back("Rachmaninov");
	composers.push_back("Debussy");
	composers.push_back("Wagner");

	cout << *(getComposer(&amp;composers,0)) << endl;

	string *pStr = getComposer(&amp;composers,1);
	cout << *pStr << endl;

	string str = *(getComposer(&amp;composers,2));
	cout << str << endl;

	*pStr = "Ravel";
	cout << composers[1] << endl;

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
Rachmaninov
Debussy
Wagner
Ravel
</pre>
<p>Let's take a look at the function, <strong>getComposer()</strong>.</p>
<pre>
string *getComposer(vector<string> *const pVec, int i) {
</pre>
<p>The <strong>string*</strong> at the start indicates that the function <strong>getComposer()</strong> is returning a pointer to a <strong>string</strong> object which is obviously not the object itself. Now, let's look at the body of the function:</p>
<pre>
	return &amp;((*pVec)[i]);
</pre>
<p><strong>(*pVec)[i]</strong> represents the i-th element of the vector pointed to by <strong>pVec</strong>. So, <strong>&amp;((*pVec)[i])</strong> becomes the address of the i-th element of the vector pointed by <strong>pVec</strong>.</p> 
<p>How about the lines in the <strong>main()</strong>.</p>
<pre>
	cout << *(getComposer(&amp;amp;composers,0)) << endl;
</pre>
<p>The code calls <strong>getComposer()</strong>, which returns a pointer to <strong>composers[0]</strong>. Then, the line sends the <strong>string</strong> object pointed by the pointer to <strong>cout</strong>, and as a result, "Rachmaninov" is displayed.</p>
<p>The next output:</p>
<pre>
	string *pStr = getComposer(&amp;amp;composers,1);
	cout << *pStr << endl;
</pre>
<p>Here, we assign a returned pointer to another pointer, <strong>pStr</strong>. Then we send <strong>*pStr</strong> to <strong>cout</strong> to print out "Debussy".</p>
<p>The third output:</p>
<pre>
	string str = *(getComposer(&amp;composers,2));
	cout << str << endl;
</pre>
<p>We assign the value pointed to by a returned pointer to a variable.
The call to <strong>getComposer()</strong> returns a pointer to <strong>composer[2]</strong>. But it can't assign the pointer returned to <strong>str</strong> because <strong>str</strong> is a <strong>string</strong> object not a pointer. Instead, the compiler makes a copy of the <strong>string</strong> object to which the pointer points and assigns that object to <strong>str</strong>. An assignment like this one, where an object is copied, is more expensive that the assignment of one pointer to another.</p>
<p>Now, the final out of the code:</p>
<pre>
	*pStr = "Ravel";
	cout << composers[1] << endl;
</pre>
<p>We can modify the object to which a returned pointer points. Because <strong>pStr</strong> points to the element in position 1 of <strong>composer</strong>, this code alters <strong>composer[1]</strong>. As a result, <strong>composer[1]</strong> is now changed to "Ravel" from "Debussy".</p>
<br />
<br />



<div class="subtitle" id="pointerstofunctions">Pointers to Functions / Function Pointers</div>
<p>As a start, let's think about what the functions are.</p>
<P>Functions, like data items, have addresses. A function's address is the memory address at which the stored machine language code for the function begins. Normally, it's neither important nor useful for us, but it can be useful to a program. For example, it's possible to write a function that takes the address of another function as an argument. That enables the first function to find the second function and run it.</p>
<p>That approach is more awkward than simply having the first function call the second one directly, but it leaves open the possibility of passing different function addresses at different times. That means the first function can use different functions at different times.</p>
<p>Functions are not objects, and there is no way to copy or assign them, or to pass them as arguments directly. In particular, there is no way for a program to create or modify a function. Only the compiler can do that. All that a program can ever do with a function is <strong>call it</strong> or <strong>take its address</strong>.</p>
<p>Nevertheless, we can call a function with another function as an argument. What really happens is that the compiler secretly translates such calls so as to use pointers to functions instead of using functions directly.</p>
<p>In fact, C++ allows operations with pointers to functions. The typical use of this is for passing a function as an argument to another function, since these cannot be passed dereferenced. </p>
<p>In other words, pointers to functions behave similarly to any other pointers. Once we have dereferenced such a pointer, however, all we can do with the resulting function is call it - or take the function's address yet again.</p> 
<br />


<div class="subtitle_2nd" id="declarepointertofunctions">Declaring a Pointer to a Function</div>
<p>Declaration of pointers to functions resembles other declarations. For example, just as we write</p>
<pre>
int *p;
</pre>
<p>to say that <strong>*p</strong> has type <strong>int</strong> and implying that <strong>p</strong> is a pointer, we may write </p>
<pre>
int (*pf)(int);
</pre>
<p>to say that if we dereference <strong>pf</strong>, and call it with an <strong>int</strong> argument, the result has type <strong>int</strong>. By implication, <strong>pf</strong> is a pointer to a function that takes an <strong>int</strong> argument and returns an <strong>int</strong> result.</p>
<p>Because all that we can do with a function is to take its address or call it, any use of a function that is not a call is assumed to be taking its address, even without an explicit &amp;.</p>
<p>Suppose we have a function with the following prototype:</p>
<pre>
int f(int);	//prototype
</pre>
<p>Note that it look just like our declaration of pointer to a function:</p>
<pre>
int (*pf)(int);
</pre>
<p>Because <strong>f</strong> is a function, so is  <strong>(*pf)</strong>. And if <strong>(*pf)</strong> is a function, then <strong>pf</strong> must be a pointer to a function.</p>
<p>The declaration requires the parentheses around <strong>*pf</strong> to provide the proper operator precedence. Parentheses have a higher precedence than the * operator, so <strong>*pf(int)</strong> means <strong>pf()</strong> is a function that returns a pointer while <strong>(*pf)(int)</strong> means <strong>pf</strong> is a pointer to a function.</p>
<pre>
int (*pf)(int);	// pf points to a function that returns int
int *pf(int);	// pf() is a function that returns a pointer to int
</pre>
<p>Once we declare <strong>pf</strong> properly, we can assign to it the address of a matching function:</p>
<pre>
int f(int);
int (*pf)(int);
pf = f;		// pf now points to the f() function
</pre>
<br />


<div class="subtitle_2nd" id="invokingfunction">Invoking a Function Using a Pointer</div>
<p>As we discussed in the previous section, <strong>(*pf)</strong> serves as a name of a function.</p>
<pre>
int f(int);
int (*pf)(int);
pf = f;			// pf now points to the f() function
int i = f(4);		// call f() using the function name
int j = (*pf)(4);	// call f() using the pointer pf
int k = pf(5)		// also call f() using the pointer pf
</pre>
<p>Here is an example using a pointer to a function.</p>
<pre>
#include &lt;iostream&gt;  
using namespace std;

int operation (int i, int j, int (*pf)(int,int)) {
	int k;
	k = (*pf)(i,j);
	/* This works, too.
  	k = pf(i,j) 
	*/
	return k;
}

int addition (int a, int b) { 
	return a+b; 
}

int division (int a, int b) { 
	return a/b; 
}

int main()  
{  	
	int m = operation (10, 5, addition);
	int n = operation (10, 5, division);

	cout << "m = " << m << endl;
	cout << "n = " << n << endl;

	return 0;
}
</pre> 
<p>Output is:</p>
<pre>
m = 15
n = 2
</pre>
<br />
<br />
<div class="subtitle" id="nullpointer">Null Pointer</div>
<p>In C++, a pointer with the value <strong>0</strong> is called the <strong>null pointer</strong>. C++ guarantees that the null pointer never points to valid data, so it is often used to indicate failure for operators or functions that otherwise return valid pointers.</p>
<pre>
int * p;
p = 0; 
</pre>

<br />
<div class="subtitle_2nd" id="nullpointervsvoidpointer">Null Pointer vs. void Pointer</div>
<ul>
	<li>null pointer <br />
	<ol>
	<li>A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere". </li>
	<li> A null pointer refers to the value stored in the pointer itself .</li>
	</ol>
	</li>
	<li>void pointer <br />
	<ol>
	<li>A void pointer is a special type of pointer that can point to somewhere without a specific type. </li>
	<li>A void pointer refers to the type of data it points to.</li>
	</ol>
	</li>
</ul>
<br />

<br />
<div class="subtitle_2nd" id="nullpointervsreference">Null Pointer vs. Null Reference</div>
<p>There is no such thing as a <strong>null reference</strong>. A reference must always refer to some object. As a result, if we have a variable whose purpose is to refer to another object, but it is possible that there might not be an object to refer to, we should make the variable a pointer, because then we can set it to <strong>null</strong>. On the other hand, if the variable must always refer to an object, i.e., if our design does not allow for the possibility that the variable is <strong>null</strong>, we should make the variable a reference.</p>
<br />
<br />

<div class="subtitle" id="voidpointer">Void Pointer (void*)</div>
<p>The type <strong>void*</strong> means "<strong>pointer to some memory that the compiler doesn't know the type of</strong>."<br />
We are using <strong>void*</strong> when we want to transmit an address between pieces of code that really don't know each other's type.</p>
<p>Normally we use it in the following cases:</p>
<ul>
	<li>A type of pointer that points to memory without knowing what kinds of objects reside in that memory.</li>
	<li>An operation to tell the compiler what kind of type to assume for memory pointed to by one of those pointers.</li>
</ul>
<p>There are no objects of type <strong>void</strong>. but we use <strong>void</strong> to mean <strong>no value returned</strong>:</p>
<pre>
void v;     // error because there are no object of type void
void v();   // v() return nothing - v() does not return an object of type void
</pre>
<p>A pointer to any object type can be assigned to a <strong>void*</strong>:</p>
<pre>
void* ptr1 = new int;          //OK: int* converted to void*
void* ptr2 = new double[100]   //OK: double* converted to void*
</pre>
<p>Because the compiler doesn't know what a <strong>void*</strong> points to, we should let the compiler know:</p>
<pre>
void function(void *pvoid)
{
	void* pvoid2 = pvoid;     // copying is OK (copying is what void*s are for)
	double* pd = pvoid;       // error: cannot convert void* to double*
	*pvoid = 7;               // error: cannot dereference a void*
	int* pi = static_cast&lt;int*&gt;(pvoid)  // OK: explicit conversion
}
</pre>
<p>For more info on <strong>void*</strong>, goto <a href="pointers2.html#voidpointers">Pointers II- void Pointers</a>.
<br />
<br />
<br /><br />

<img src="images/pointers3/JiriSan.png" alt="JiriSan"/>
<br />
<br />
<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers I</a></li>
   <li><a href="pointers2.html">Pointers II - void*, Pointer/Array, and Pointer to Pointer</a></li>
   <li><a href="pointers3.html">Pointers III - Pointer to Function, Null Pointer</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />



<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
